import Cookies from 'js-cookie'
// import { findIndex } from 'utils'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LEN = 15

const PLAY_KEY = '__play__'
const PLAY_MAX_LEN = 200

const PLAY_LIST = '__playList_'
const PLAY_LIST_LEN = 500

const CURRENT_SONG_INDEX = '_index_'

// 插入
function insertArray (arr, val, func, maxLen) {
  const index = arr.findIndex(func)
  console.log(arr, val, index)
  if (index >= 0) {
    return
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

// 删除
function deleteFromArray (arr, func) {
  const index = arr.findIndex(func)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

// 保存搜索记录
export function saveSearch (query) {
  let searches = Cookies.get(SEARCH_KEY) || []
  insertArray(searches, query, (item) => {
    return item === query
  }, SEARCH_MAX_LEN)
  Cookies.set(SEARCH_KEY, searches)
  return searches
}

// 获取搜索记录
export function loadSearch () {
  return Cookies.get(SEARCH_KEY)
}

// 删除搜索内容
export function deleteSearch (query) {
  let searches = Cookies.get(SEARCH_KEY) || []
  deleteFromArray(searches, (item) => {
    return item === query
  })
  Cookies.set(SEARCH_KEY, searches)
  return searches
}

// 清空搜索记录
export function clearSearch () {
  Cookies.remove(SEARCH_KEY)
  return []
}

// 设置播放列表
export function savePlay (song) {
  let songs = loadPlay().length ? JSON.parse(loadPlay()) : []
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, PLAY_MAX_LEN)
  Cookies.set(PLAY_KEY, songs)
  return songs
}

// 获取播放列表
export function loadPlay () {
  return Cookies.get(PLAY_KEY) || []
}

// 设置播放列表
export function setCurrentIndex (index) {
  Cookies.set(CURRENT_SONG_INDEX, index)
  return index
}

// 播放歌曲index
export function getCurrentIndex () {
  return Cookies.get(CURRENT_SONG_INDEX)
}

// 保存播放列表
export function savePlayList (song) {
  let songs = JSON.parse(Cookies.get(PLAY_LIST)) || []
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, PLAY_LIST_LEN)
  Cookies.set(PLAY_LIST, songs)
  return songs
}

// 获取播放列表
export function getPlayList () {
  return Cookies.get(PLAY_LIST)
}
